package com.ds.esd.admin.team;

import com.ds.client.JDSSessionFactory;
import com.ds.common.JDSException;
import com.ds.common.org.CtOrg;
import com.ds.common.org.CtOrgManager;
import com.ds.common.org.CtPerson;
import com.ds.common.org.service.OrgAdminService;
import com.ds.common.util.CnToSpell;
import com.ds.common.util.StringUtility;
import com.ds.config.ErrorListResultModel;
import com.ds.config.ErrorResultModel;
import com.ds.config.ListResultModel;
import com.ds.config.ResultModel;
import com.ds.context.JDSActionContext;
import com.ds.engine.ConnectInfo;
import com.ds.engine.JDSSessionHandle;
import com.ds.enums.db.MethodChinaName;
import com.ds.esd.client.ESDClient;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.client.Project;
import com.ds.esd.project.config.ProjectConfig;
import com.ds.esd.project.enums.ProjectRoleType;
import com.ds.jds.core.User;
import com.ds.jds.core.esb.EsbUtil;
import com.ds.org.*;
import com.ds.org.conf.OrgConstants;
import com.ds.server.JDSClientService;
import com.ds.server.JDSServer;
import com.ds.server.OrgManagerFactory;
import com.ds.web.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.ds.server.OrgManagerFactory.getOrgManager;

@MethodChinaName(cname = "系统用户接口")
@Controller
@RequestMapping("/admin/org/")
public class OrgService {


    @MethodChinaName(cname = "用户登录")
    @RequestMapping(method = RequestMethod.POST, value = "login")
    public @ResponseBody
    ResultModel<User> login(String userName, String password) {
        ResultModel<User> result = new ResultModel<User>();
        try {

            HttpServletRequest request = (HttpServletRequest) JDSActionContext.getActionContext().getHttpRequest();

            if (request != null && request.getSession(true) != null) {
                request.getSession(true).invalidate();
            }

            OrgManager orgManager = OrgManagerFactory.getOrgManager(OrgConstants.CONFIG_KEY);

            Person person = null;
            userName = userName.toLowerCase();
            JDSClientService client = null;
            // 根据用户名密码获取用户
            boolean login = true;
            person = orgManager.getPersonByAccount(userName.toLowerCase());
            login = orgManager.verifyPerson(userName.toLowerCase(), password);
            ConnectInfo connect = new ConnectInfo(userName, person.getID(), person.getPassword());

            person = orgManager.getPersonByAccount(userName);
            // 封装登录信息
            ConnectInfo connectInfo = new ConnectInfo(person.getID(), person.getAccount(), person.getPassword());
            // 获取session
            JDSSessionFactory factory = new JDSSessionFactory(JDSActionContext.getActionContext());

            JDSSessionHandle sessionHandle = factory.createSessionHandle();


            JDSActionContext.getActionContext().getContext().put(JDSActionContext.JSESSIONID, sessionHandle.getSessionID());
            request.setAttribute(JDSActionContext.JSESSIONID, sessionHandle.getSessionID());


            // 将该标识码添加到session中
            JDSActionContext.getActionContext().getSession().put(JDSActionContext.SYSCODE, "org");


            Set<JDSSessionHandle> sessionHandleList = JDSServer.getInstance().getSessionHandleList(connectInfo);

            // 注销掉多余的SESSION
            List<JDSSessionHandle> newsessionHandleList = new ArrayList<JDSSessionHandle>();

            client = factory.newClientService(sessionHandle, JDSActionContext.getActionContext().getConfigCode());

            client.connect(connectInfo);


            User user = new User();
            user.setAccount(userName.toLowerCase());
            user.setId(person.getID());
            user.setEmail(person.getEmail());
            user.setName(person.getName());
            user.setSessionId(sessionHandle.getSessionID());

            user.setPhone(person.getMobile());
            result.setData(user);


            // result.setData(connect);
        } catch (PersonNotFoundException e) {

            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.NOTLOGINEDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.NOTLOGINEDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());
        }


        return result;

    }

    @MethodChinaName(cname = "用户退出")
    @RequestMapping(method = RequestMethod.POST, value = "logout")
    public @ResponseBody
    ResultModel<Boolean> logout() {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            OrgManager orgManager = OrgManagerFactory.getOrgManager(OrgConstants.CONFIG_KEY);
            this.getClient().disconnect();
            JDSActionContext.getActionContext().getContext().remove(JDSActionContext.JSESSIONID);
            HttpServletRequest request = (HttpServletRequest) JDSActionContext.getActionContext().getHttpRequest();
            request.removeAttribute(JDSActionContext.JSESSIONID);
            result.setData(true);
        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(JDSException.NOTLOGINEDERROR);
            ((ErrorResultModel) result).setErrdes(e.getMessage());
        }


        return result;

    }

    Org getTopOrg() throws JDSException {
        List<Org> orgs = OrgManagerFactory.getOrgManager(this.getClient().getConfigCode()).getTopOrgs(JDSActionContext.getActionContext().getSystemCode());
        if (orgs == null || orgs.size() == 0) {
            throw new JDSException("系统信息错误");
        }
        return orgs.get(0);
    }


    @MethodChinaName(cname = "添加开发成员")
    @RequestMapping(method = RequestMethod.POST, value = "addDevPersons")
    public @ResponseBody
    ResultModel<Boolean> addDevPersons(String projectName, ProjectRoleType group, String id) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        String[] personIdArr = StringUtility.split(id, ";");
        try {
            Project project = getClient().getProjectByName(projectName);
            ProjectConfig config = project.getConfig();
            for (String personId : personIdArr) {
                config.addDevPersons(group, personId);
            }
            project.updateConfig(config);


        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(e.getErrorCode());
            ((ErrorResultModel) result).setErrdes(e.getMessage());
        }
        return result;

    }

    @MethodChinaName(cname = "移除开发成员")
    @RequestMapping(method = RequestMethod.POST, value = "removeDevPersons")
    public @ResponseBody
    ResultModel<Boolean> removeDevPersons(String projectName, ProjectRoleType group, String iD) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();

        try {
            Project project = getClient().getProjectByName(projectName);
            ProjectConfig config = project.getConfig();
            config.removeDevPersons(group, iD);
            project.updateConfig(config);

        } catch (JDSException e) {
            result = new ErrorResultModel();
            ((ErrorResultModel) result).setErrcode(e.getErrorCode());
            ((ErrorResultModel) result).setErrdes(e.getMessage());
        }


        return result;

    }


    @MethodChinaName(cname = "获取开发成员列表")
    @RequestMapping(method = RequestMethod.POST, value = "getDevPersons")
    public @ResponseBody
    ListResultModel<List<Person>> getDevPersons(String projectName, ProjectRoleType group) {
        ListResultModel<List<Person>> userStatusInfo = new ListResultModel<List<Person>>();

        List<Person> xuiPersons = null;
        try {
            Project project = getClient().getProjectByName(projectName);
            xuiPersons = project.getDevPersons(group);
        } catch (JDSException e) {
            e.printStackTrace();
        }
        userStatusInfo = PageUtil.getDefaultPageList(xuiPersons);
        return userStatusInfo;

    }

    public ESDClient getClient() throws JDSException {

        ESDClient client = ESDFacrory.getESDClient();

        return client;
    }

    @MethodChinaName(cname = "获取开发组织")
    @RequestMapping(value = {"getOrgs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIOrg> getOrgs() {
        ResultModel<XUIOrg> userStatusInfo = new ResultModel<XUIOrg>();

        try {
            Org org = getTopOrg();
            XUIOrg xuiOrg = new XUIOrg(org, false);
            userStatusInfo.setData(xuiOrg);
        } catch (JDSException e) {
            e.printStackTrace();
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel<XUIOrg>) userStatusInfo).setErrdes(e.getMessage());
        }


        return userStatusInfo;
    }

    @MethodChinaName(cname = "获取子节点")
    @RequestMapping(value = {"getChildOrgs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<Org>> getChildOrgs(String orgId) {
        ListResultModel<List<Org>> userStatusInfo = new ListResultModel<List<Org>>();
        List<Org> xuiOrgs = new ArrayList<Org>();

        try {
            if (orgId == null || orgId.equals("")) {
                orgId = this.getTopOrg().getOrgId();
            }
            Org org = getOrgManager().getOrgByID(orgId);
            userStatusInfo = PageUtil.getDefaultPageList(org.getChildrenList());
        } catch (JDSException e) {
            userStatusInfo = new ErrorListResultModel();
            ((ErrorListResultModel) userStatusInfo).setErrdes(e.getMessage());
        } catch (OrgNotFoundException e) {
            userStatusInfo = new ErrorListResultModel();
            ((ErrorListResultModel) userStatusInfo).setErrdes(e.getMessage());
        }

        return userStatusInfo;
    }

    @MethodChinaName(cname = "添加组织管理员")
    @RequestMapping(value = {"addLeader"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> addLeader(String personId, String orgId) {
        ResultModel<Boolean> userStatusInfo = new ResultModel<Boolean>();
        try {
            CtOrg org = (CtOrg) getOrgManager().getOrgByID(orgId);
            Person person = getOrgManager().getPersonByID(personId);
            org.setLeader(personId);
        } catch (Exception e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        }
        return userStatusInfo;
    }

    @MethodChinaName(cname = "获取成员节点数据")
    @RequestMapping(value = {"getPersonTree"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIOrg> getPersonTree(String iD) {
        ResultModel<XUIOrg> userStatusInfo = new ResultModel<XUIOrg>();
        List<Person> xuiPersons = new ArrayList<Person>();

        try {
            if (iD == null || iD.equals("")) {
                iD = this.getTopOrg().getOrgId();
            }
            Org org = getOrgManager().getOrgByID(iD);
            XUIOrg xuiorg = new XUIOrg(org, true);
            userStatusInfo.setData(xuiorg);
        } catch (OrgNotFoundException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        } catch (JDSException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        }
        return userStatusInfo;
    }

    @MethodChinaName(cname = "获取机构节点数据")
    @RequestMapping(value = {"getOrgnTree"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<XUIOrg> getOrgnTree(String iD) {

        ResultModel<XUIOrg> userStatusInfo = new ResultModel<XUIOrg>();
        List<Person> xuiPersons = new ArrayList<Person>();

        try {
            if (iD == null || iD.equals("")) {
                iD = this.getTopOrg().getOrgId();
            }
            Org org = getOrgManager().getOrgByID(iD);
            XUIOrg xuiorg = new XUIOrg(org, false);
            userStatusInfo.setData(xuiorg);
        } catch (OrgNotFoundException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        } catch (JDSException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        }
        return userStatusInfo;
    }

    @MethodChinaName(cname = "查找成员")
    @RequestMapping(value = {"findPerson"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<Person>> findPerson() {

        ListResultModel<List<Person>> userStatusInfo = new ListResultModel<List<Person>>();
        List<Person> xuiPersons = new ArrayList<Person>();

        List<Person> persons = getOrgManager().getPersons();
        userStatusInfo = PageUtil.getDefaultPageList(persons);


        return userStatusInfo;
    }

    @MethodChinaName(cname = "获取成员")
    @RequestMapping(value = {"getPersons"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<Person>> getPersons(String orgId) {

        ListResultModel<List<Person>> userStatusInfo = new ListResultModel<List<Person>>();
        List<Person> xuiPersons = new ArrayList<Person>();
        try {
            if (orgId == null || orgId.equals("")) {
                orgId = this.getTopOrg().getOrgId();
            }
            Org org = getOrgManager().getOrgByID(orgId);
            userStatusInfo = PageUtil.getDefaultPageList(org.getPersonList());
        } catch (Exception e) {
            userStatusInfo = new ErrorListResultModel();
            ((ErrorListResultModel) userStatusInfo).setErrdes(e.getMessage());
        }

        return userStatusInfo;
    }

    @MethodChinaName(cname = "保存成员信息")
    @RequestMapping(value = {"savePerson"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> savePerson(@RequestBody CtPerson person) {
        ResultModel<Boolean> userStatusInfo = new ResultModel<Boolean>();
        try {
            if (person.getAccount() == null || person.getAccount().equals("")) {
                person.setAccount(CnToSpell.getFullSpell(person.getName()));
            }
            getOrgService().savePerson(person).get();
            CtOrgManager manager = (CtOrgManager) OrgManagerFactory.getOrgManager();
            manager.clearOrgCache(person.getOrgId());

        } catch (JDSException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        }
        return userStatusInfo;

    }

    @MethodChinaName(cname = "保存机构信息")
    @RequestMapping(value = {"saveOrg"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> saveOrg(@RequestBody CtOrg org) {
        ResultModel<Boolean> userStatusInfo = new ResultModel<Boolean>();
        try {
            getOrgService().saveOrg(org).get();
            CtOrgManager manager = (CtOrgManager) OrgManagerFactory.getOrgManager();
            manager.clearOrgCache(org.getOrgId());
        } catch (JDSException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        }
        return userStatusInfo;

    }

    @MethodChinaName(cname = "移除成员")
    @RequestMapping(value = {"delPerson"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> delPerson(String personId) {
        ResultModel<Boolean> userStatusInfo = new ResultModel<Boolean>();

        try {
            CtOrgManager manager = (CtOrgManager) OrgManagerFactory.getOrgManager();
            Person person = manager.getPersonByID(personId);
            getOrgService().delPerson(personId).get();
            manager.clearOrgCache(person.getOrgId());
        } catch (JDSException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        } catch (PersonNotFoundException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        }
        return userStatusInfo;
    }

    @MethodChinaName(cname = "移除组织")
    @RequestMapping(value = {"delOrg"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> delOrg(String orgId) {
        ResultModel<Boolean> userStatusInfo = new ResultModel<Boolean>();

        try {
            CtOrgManager manager = (CtOrgManager) OrgManagerFactory.getOrgManager();
            Org org = manager.getOrgByID(orgId);

            getOrgService().delOrg(orgId).get();
            manager.clearOrgCache(org.getParentId());
        } catch (JDSException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        } catch (OrgNotFoundException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        }
        return userStatusInfo;
    }

    OrgAdminService getOrgService() {
        OrgAdminService service = EsbUtil.parExpression("$OrgAdminService", OrgAdminService.class);
        return service;
    }


}
